const chatHistory = [{
    role: 'system',
    content: '你是一个智能游戏助理，你的回答总是正确、有用且简洁，专注于提供游戏攻略、技巧和解决方案。'
}];

// 在文件顶部添加常量
const HISTORY_KEY = 'chat_history';
const HISTORY_FILE = './chatHistory.txt';

// 在DOMContentLoaded事件监听器中初始化历史记录
document.addEventListener('DOMContentLoaded', () => {
    const sendBtn = document.getElementById('send-btn');
    const userInput = document.getElementById('user-input');

    sendBtn.addEventListener('click', sendMessage);
    userInput.addEventListener('keypress', e => {
        if (e.key === 'Enter') sendMessage();
    });

    // 导航栏点击处理
    // 在导航栏点击处理中添加游戏库显示逻辑
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', () => {
            // 移除所有激活状态
            document.querySelectorAll('.nav-item').forEach(nav => {
                nav.classList.remove('active');
            });
            // 添加当前激活状态
            item.classList.add('active');
        });
    });
    initHistory();
});

// 初始化历史记录
function initHistory() {
    const historyList = document.getElementById('history-list');
    historyList.innerHTML = '<div class="loading-text">加载历史记录中...</div>';

    loadHistory().then(history => {
        if (history.length === 0) {
            historyList.innerHTML = '<div class="empty-history">暂无历史记录</div>';
        } else {
            renderHistory(history);
        }
    }).catch(error => {
        historyList.innerHTML = `<div class="error-message">加载失败: ${error.message}</div>`;
    });
}

async function loadHistory() {
    try {
        const response = await fetch('/api/history');
        const data = await response.json();
        return Array.isArray(data) ? data : [];
    } catch (error) {
        console.error('加载历史记录失败:', error);
        return [];
    }
}

function renderHistory(history) {
    const historyList = document.getElementById('history-list');
    if (!historyList) {
        console.error('找不到历史列表容器');
        return;
    }
    historyList.innerHTML = Array.isArray(history) ?
        history.map((item, index) => `
            <div class="history-item" data-index="${index}">
                <div class="history-time">${item.timestamp}</div>
                <div class="history-title">${item.messages[0]?.content?.substring(0, 15) || '新对话'}...</div>
            </div>
        `).join('') :
        '';

    // Add event listeners properly
    document.querySelectorAll('.history-item').forEach(item => {
        item.addEventListener('click', () => {
            const index = item.dataset.index;
            loadChatHistory(index);
        });

        // Add hover effects here
        item.addEventListener('mouseenter', () => {
            item.style.transform = 'translateX(10px)';
            item.style.boxShadow = '2px 4px 6px rgba(0,0,0,0.1)';
        });

        item.addEventListener('mouseleave', () => {
            item.style.transform = 'translateX(0)';
            item.style.boxShadow = 'none';
        });
    });
}

// 由于原选择内容仅为一个闭合花括号，推测可能是代码结构不完整，这里暂时添加一个空函数声明作为示例
function emptyFunction() {
    // 此函数为空
}

// 保存当前对话
function saveCurrentChat() {
    const history = loadHistory();
    history.unshift({
        timestamp: new Date().toISOString(),
        messages: [...chatHistory]
    });

    localStorage.setItem(HISTORY_KEY, JSON.stringify(history));
    renderHistory(history);
    chatHistory.length = 0; // 清空当前对话
}

// 在sendMessage函数末尾调用保存方法
async function sendMessage() {
    const userInput = document.getElementById('user-input');
    const chatbox = document.getElementById('chatbox');
    const sendBtn = document.getElementById('send-btn');

    if (!userInput.value.trim()) return;

    // 立即清空输入框
    const userMessage = userInput.value; // 先保存用户输入
    userInput.value = ''; // 立即清空输入框

    // 禁用输入框和发送按钮
    userInput.disabled = true;
    sendBtn.disabled = true;
    sendBtn.innerHTML = '<div class="loading-dots"><div></div><div></div><div></div><div></div></div>';

    // 添加用户消息
    chatHistory.push({
        role: 'user',
        content: userMessage
    }); // 使用保存的输入
    appendMessage(userMessage, 'user');

    try {
        const response = await fetch('http://localhost:8001/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                messages: chatHistory
            })
        });

        const assistantMsg = await processStreamResponse(response);
        chatHistory.push({
            role: 'assistant',
            content: assistantMsg
        });

    } catch (error) {
        console.error('请求错误:', error);
        appendMessage('对话服务暂时不可用，请稍后再试', 'assistant');
    } finally {
        // 移除原来的清空操作
        sendBtn.disabled = false;
        sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
        chatbox.scrollTop = chatbox.scrollHeight;
    }
}

async function processStreamResponse(response) {
    const chatbox = document.getElementById('chatbox');
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let assistantResponse = '';

    const msgDiv = document.createElement('div');
    msgDiv.className = 'message assistant-message';
    chatbox.appendChild(msgDiv);

    while (true) {
        const {
            done,
            value
        } = await reader.read();
        if (done) break;

        const chunk = decoder.decode(value);
        const lines = chunk.split('\n\n');

        lines.forEach(line => {
            if (line.startsWith('data: ')) {
                try {
                    const data = JSON.parse(line.slice(6));
                    if (data.token) {
                        assistantResponse += data.token;
                        msgDiv.innerHTML = assistantResponse;
                    }
                } catch (e) {
                    console.warn('解析错误:', e);
                }
            }
        });
    }

    return assistantResponse;
}

function appendMessage(content, role) {
    const chatbox = document.getElementById('chatbox');
    const msgDiv = document.createElement('div');
    msgDiv.className = `message ${role}-message`;
    msgDiv.textContent = content;
    chatbox.appendChild(msgDiv);
    chatbox.scrollTop = chatbox.scrollHeight;
}

// 加载历史对话
function loadChatHistory(index) {
    const history = loadHistory();
    const chat = history[index];
    const chatbox = document.getElementById('chatbox');

    chatbox.innerHTML = chat.messages
        .filter(msg => msg.role !== 'system')
        .map(msg => `
            <div class="message ${msg.role}-message">
                ${msg.content}
            </div>
        `).join('');
}

// 添加保存到文件的方法
function saveToFile(content) {
    const blob = new Blob([content], {
        type: 'text/plain'
    });
    const a = document.createElement('a');
    a.download = 'chatHistory.txt';
    a.click();
}

// 修改历史记录保存逻辑
// 在DOMContentLoaded事件中添加按钮监听
document.addEventListener('DOMContentLoaded', () => {
    const saveBtn = document.getElementById('save-btn');
    saveBtn.addEventListener('click', saveChatHistory);
});

// 新增保存函数
async function saveChatHistory() {
    await fetch('/api/history', {
        method: 'POST',
        body: JSON.stringify({
            timestamp: new Date().toLocaleString(),
            messages: chatHistory // 当前聊天记录
        })
    });
}

// 修改初始化后的服务端检测
document.addEventListener('DOMContentLoaded', () => {
    // 检测服务端是否在线
    fetch('/api/history')
        .catch(() => {
            alert('错误：后端服务未启动！\n请运行命令：node server.js');
        });
});
document.querySelector('.nav-item:nth-child(2)').addEventListener('click', () => {
    const modal = document.getElementById('game-library');
    modal.style.display = 'block';
    document.addEventListener('keydown', handleEscape);
});

// 设置弹窗控制
// 优化后的弹窗控制逻辑
document.querySelector('.nav-item:last-child').addEventListener('click', () => {
    const modal = document.getElementById('settings-modal');
    modal.style.display = 'block';
    document.addEventListener('keydown', handleEscape);
});

function handleEscape(e) {
    if (e.key === 'Escape') {
        document.getElementById('settings-modal').style.display = 'none';
        document.removeEventListener('keydown', handleEscape);
    }
}

// 优化关闭按钮事件绑定（在DOMContentLoaded事件内部添加）
document.addEventListener('DOMContentLoaded', () => {
    // 新增关闭按钮事件监听
    document.getElementById('settings-modal').querySelector('.close-btn').addEventListener('click', () => {
        document.getElementById('settings-modal').style.display = 'none';
        document.removeEventListener('keydown', handleEscape);
    });
});

// 优化游戏库弹窗关闭逻辑
document.querySelector('#game-library .close-btn').addEventListener('click', () => {
    document.getElementById('game-library').style.display = 'none';
    document.removeEventListener('keydown', handleEscape);
});

// 增强ESC关闭功能
function handleEscape(e) {
    if (e.key === 'Escape') {
        document.getElementById('settings-modal').style.display = 'none';
        document.getElementById('game-library').style.display = 'none';
        document.removeEventListener('keydown', handleEscape);
    }
}

// 优化外部点击关闭
window.onclick = function (event) {
    const settingsModal = document.getElementById('settings-modal');
    const gameLibrary = document.getElementById('game-library');

    if (event.target === settingsModal) {
        settingsModal.style.display = 'none';
    }
    if (event.target === gameLibrary) {
        gameLibrary.style.display = 'none';
    }
};

// 新增关闭动画效果
document.querySelectorAll('.modal .close-btn').forEach(btn => {
    btn.addEventListener('click', () => {
        btn.parentElement.parentElement.style.animation = 'modalFadeOut 0.3s ease';
    });
});
// document.querySelector('.close-modal').addEventListener('click', function () {
//     document.getElementById('settings-modal').style.display = 'none';
// });

window.onclick = function (event) {
    const modal = document.getElementById('settings-modal');
    if (event.target === modal) {
        modal.style.display = 'none';
    }
};

// 主题切换功能
// 修改主题切换事件监听
// document.getElementById('theme-select').addEventListener('change', function (e) {
//     document.body.className = e.target.value;
//     // 强制重绘所有元素
//     document.querySelectorAll('*').forEach(el => el.style.animation = 'none');
//     localStorage.setItem('theme', e.target.value);
// });
// 同步更新导航栏样式
document.querySelectorAll('.nav-item').forEach(item => {
    console.log(item.textContent);

    // item.style.backgroundColor = e.target.value === 'dark' ? '#2d2d2d' : '#ffffff';
});
// localStorage.setItem('theme', e.target.value);

// 在DOMContentLoaded事件中添加新聊天按钮监听


document.getElementById('add').addEventListener('click', () => {
    console.log('New Chat clicked');
    document.getElementById('user-input').value = ''; // 清空输入框
    document.getElementById('chatbox').innerHTML = ''; // 清空聊天框
    chatHistory.length = 0; // 清空内存中的聊天记录
});